import os
from streamlit_model.streamlit_utils.xmind_utils import get_xmind_files_in_xmind_dir
import streamlit as st
import time
from datetime import datetime, timedelta


def xmind_files_case():
    st.text("查看最近几天生成的用例文件（.xmind）")

    now = datetime.now()
    three_days_ago = now - timedelta(days=3)
    three_days_ago_timestamp = time.mktime(three_days_ago.timetuple())

    xmind_files = get_xmind_files_in_xmind_dir()
    recent_files = []

    if xmind_files:
        for file_path in xmind_files:
            mod_time = os.path.getmtime(file_path)
            if mod_time >= three_days_ago_timestamp:
                recent_files.append((file_path, mod_time))

        recent_files.sort(key=lambda x: x[1], reverse=True)

        for file_path, mod_time in recent_files:
            file_name = os.path.basename(file_path)
            formatted_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(mod_time))

            col1, col2, col3 = st.columns([3, 1, 1])
            with col1:
                st.write(f"📄 **{file_name}**（修改时间：{formatted_time}）")
            with col2:
                # 三个按钮水平排布
                d1, d2, d3 = st.columns(3)
                with d1:
                    with open(file_path, "rb") as f:
                        st.download_button(
                            "⬇️下载",
                            data=f,
                            file_name=file_name,
                            mime="application/octet-stream",
                            key=f"dl_{file_path}"
                        )
                with d2:
                    if st.button("🗑️删除", key=f"del_{file_path}"):
                        try:
                            os.remove(file_path)
                            st.success("已删除")
                            st.rerun()
                        except Exception as e:
                            st.error(str(e))
    else:
        st.warning("最近三天内没有生成的用例文件")
